package com.zifan.mail.receiver;

import com.rabbitmq.client.Channel;
import com.zifan.sever.bean.Employee;
import com.zifan.sever.constant.MailConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * 消费者 接收消息并发送邮件
 * @author Zifan
 * @date 2021年05月18日20:42
 */
@Component
@Slf4j
public class MailReceiver {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue,
            exchange = @Exchange(value = MailConstants.MAIL_EXCHANGE_NAME),
            key = {MailConstants.MAIL_ROUTING_KEY_NAME}
    ))
    public void handel(Message message, Channel channel){
        //这样就拿到了员工类
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        //消息序号
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String) headers.get("spring_returned_message_correlation");
        //获取redisforh哈希
        HashOperations forHash = redisTemplate.opsForHash();
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            //发邮件前判断，如果redis有这个msgid，那就说明发送过了，就不发了
            if (forHash.entries("mail_log").containsKey(msgId)){
                log.error("{}消息已经被消费了！",msgId);
                //别忘了确认
                channel.basicAck(tag,false);
                return;
            }
            //设置发件人
            helper.setFrom(mailProperties.getUsername());
            //设置收件人
            helper.setTo(employee.getEmail());
            //设置主题
            helper.setSubject("入职欢迎你");
            //发送日期
            helper.setSentDate(new Date());

            //邮件内容
            Context context = new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("posName",employee.getPosition().getName());
            context.setVariable("joblevelName",employee.getJoblevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail,true);
            //发送邮件
            javaMailSender.send(msg);
            log.info("邮件发送成功！");
            //发送成功，将消息id存入redis
            forHash.put("mail_log",msgId,"ok");
            //千万别忘了手动确认,tag确认哪条消息。参数2，是否一次确认多条？
            channel.basicAck(tag,false);
        } catch (MessagingException | IOException e) {
            /**
             * 异常时候的消息确认
             * 参数1：确认的消息id
             * 参数2：是否多条确认
             * 参数3：是否重回队列
             */
            try {
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                ex.printStackTrace();
                log.error("{}消息发送失败！",msgId);
            }
            e.printStackTrace();
            log.error("{}消息发送失败！",msgId);
        }
    }

}
